from models import db
from datetime import datetime

class Collection:
    def __init__(self, model ,schema):
        self.schema= schema
        self.model = model
    
    def get(self,func):
        def inner(*args, **kwargs):
            record = self.model.query.get(kwargs['id'])
            db.session.commit()
            func(*args, **kwargs)
            return self.schema().dump(record)
        return inner
    def post(self,func):
        def inner(*args, **kwargs):
            func(*args, **kwargs)
            print(args)
            db.session.add(self.model(args[1]))
            db.session.commit()
        return inner
    def put(self,func):
        def inner(*args, **kwargs):
            print(args)
            record = self.model.query.get(kwargs['id'])
            for key,value in args[1].items():
                setattr(record, key, value)
            db.session.commit()
            func(*args, **kwargs)
        return inner
    def delete(self,func):
        def inner(*args, **kwargs):
            record = self.model.query.get(args[1])
            if record is None:
                pass
            else:
                db.session.delete(record)
            func(*args, **kwargs)
        return inner

    def multiget(self,func):
        def inner(*args, **kwargs):
            records = self.model.query.paginate(args[1]['page'],args[1]['per_page'],False)
            func(*args, **kwargs)
            return self.schema(many=True).dump(records.items)
        return inner
        
